package com.summer.safe.config.token;

import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class TokenInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            Token annotation = method.getAnnotation(Token.class);
            if (annotation != null) {
                if(repeatDataValidator(request)){//验证时间戳及uri
                    //重复提交处理
                    response.setCharacterEncoding("UTF-8");
                    response.getWriter().print("重复提交数据，保存失败！");
                    return false;
                }else{
                    return true;
                }
            }else {
                request.setAttribute("TOKEN_FORM",System.currentTimeMillis());
            }
            return true;
        } else {//为除了注解的表单提交页面外的所有请求加上时间戳
            return super.preHandle(request, response, handler);
        }
    }

    /**
     * 验证同一个url数据是否相同提交  ,相同返回true
     * @param httpServletRequest
     * @return
     */
    public boolean repeatDataValidator(HttpServletRequest httpServletRequest){
        String token = httpServletRequest.getParameter("timestamp");
        String url = httpServletRequest.getRequestURI();
        Map<String,String> map=new HashMap<String,String>();
        map.put(url, token);

        //当前请求url
        String nowUrlToken = map.toString();
        //上次请求url
        Object preUrlToken = httpServletRequest.getSession().getAttribute("repeatData");
        //如果上一个数据为null,表示还没有访问页面
        if(preUrlToken == null){
            httpServletRequest.getSession().setAttribute("repeatData", nowUrlToken);
            return false;
        }else{//否则，再次提交数据
            //如果上次url+token和本次url+token相同，则表示重复提交数据请求
            if(preUrlToken.toString().equals(nowUrlToken)){
                return true;
            }else{//如果上次 url+token 和本次url加token不同，则不是重复提交
                //更新临时会话中的数据
                httpServletRequest.getSession().setAttribute("repeatData", nowUrlToken);
                return false;
            }
        }
    }
}
